package com.mq.common;

import java.io.*;
//序列化/反序列化
//如果需要对象实现序列化和反序列化，需要让这个类实现Serializable接口
public class BinaryTool {
    //把一个对象序列化成一个字节数组Object object--->byte[] data
    public static byte[] toBytes(Object object) throws IOException {
        //这个流对象相当于一个变长的字节数组
        //就可以把object序列化的数据逐渐的写入到 byteArrayOutputStream 中，统一转化成byte[]
        try(ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()){
            try(ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)){
                objectOutputStream.writeObject(object);
            }
            return byteArrayOutputStream.toByteArray();
        }
    }
    //把一个字节数组反序列化成一个对象byte[] data-->Object object
    public static Object fromBytes(byte[] data) throws IOException, ClassNotFoundException {
        Object object = null;
        try(ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data)){
            try(ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)){
                object = objectInputStream.readObject();
            }
            return object;
        }
    }


}
